import os
import json
import subprocess
from git import Repo
from git.exc import InvalidGitRepositoryError

def get_repo_url(directory='.'):
    """获取指定路径下git仓库的远程URL地址"""
    try:
        # 执行git命令获取远程仓库URL
        result = subprocess.run(['git', 'config', '--get', 'remote.origin.url'], cwd=directory, check=True, text=True, capture_output=True)
        return result.stdout.strip()  # 返回远程仓库URL
    except subprocess.CalledProcessError as e:
        # 处理命令执行错误
        # print(f"Error: {e.stderr.strip()}")
        return None

def scan_git_projects(directory):
    """
    扫描指定目录下的Git项目
    :param directory: 要扫描的目录路径
    :return: 包含Git项目路径的列表
    """
    git_projects = []
    for root, dirs, files in os.walk(directory):
        # 尝试初始化为Git仓库
        try:
            repo = Repo(root)
        except InvalidGitRepositoryError:
            continue  # 不是Git仓库，跳过
        else:
            git_projects.append(root)
    return git_projects
 
def scan_git_projects_to_config_json(directory):
    git_projects = []
    projects = scan_git_projects(directory)
    for path in projects:
        repo_url = get_repo_url(path)
        if '.git' in path and '/bak/' not in path and repo_url is not None:
            print(f"Git项目: {path}, 地址: {repo_url}")
            project = { "path": path, "repo_url": repo_url }
            git_projects.append(project)
    return git_projects


def save_file(filename, content):
    # 打开文件进行写入，如果文件不存在将会被创建
    with open(filename, 'w') as file:
        json.dump(content, file)

# 使用示例
scan_path = '../study'
gitscan_json = 'gitscan.json'
git_projects = scan_git_projects_to_config_json(scan_path)
save_file(gitscan_json, git_projects)